use super::cli::GenConfig;
use super::config::Config;
use std::env;
use std::error::Error;
use std::io::Write;

/// 生成配置
pub fn gen_config(args: &GenConfig) {
    let config_path = find_files(
        &args.config_path.as_str(),
        "csv",
        &args.config_path.as_str(),
    );
    if config_path.is_empty() {
        println!("在{}下 未找到csv文件", args.config_path);
        return;
    }
    gen_json_and_ini(config_path, &args.config_path, &args.name).ok();
}

///遍历目录下的文件指定后缀名的所有文件 包括子目录
fn find_files(config_path: &str, suffix: &str, project_path: &str) -> Vec<String> {
    let mut files = Vec::new();
    let paths = std::fs::read_dir(config_path).unwrap();
    for path in paths {
        let path = path.unwrap().path();
        if path.is_dir() {
            files.extend(find_files(path.to_str().unwrap(), suffix, project_path));
        } else {
            if path.to_str().unwrap().ends_with(suffix) {
                //将路径中的项目路径替换掉
                files.push(path.to_str().unwrap().replace(project_path, "").to_string());
            }
        }
    }
    files
}

fn gen_json_and_ini(
    path: Vec<String>,
    config_path: &str,
    out_name: &str,
) -> Result<(), Box<dyn Error>> {
    let out_path = env::var("CSV_UTIL_CONFIG_PATH").unwrap();
    let json_path = out_path.to_string() + "/" + out_name + ".json";
    let mut config = Config::new_by_path(&json_path);
    config.config_path = config_path.to_string();
    config.name = out_name.to_string();
    config.init_by_csv_paths(path, config_path);
    config.init_typs();
    let json_buf = std::fs::File::create(json_path).unwrap();
    let mut json_wtr = std::io::BufWriter::new(json_buf);
    json_wtr.write_all(config.to_json_string().as_bytes())?;

    Ok(())
}

pub fn test() {
    let item = String::from("[{\"mid\":297001,\"num\":1000}]");
    let mut is_number = true;
    if !item.is_empty() {
        //把字符串中的0-9和小数点过删掉
        let str = item.replace(".", "");
        let str = str.replace("0", "");
        let str = str.replace("1", "");
        let str = str.replace("2", "");
        let str = str.replace("3", "");
        let str = str.replace("4", "");
        let str = str.replace("5", "");
        let str = str.replace("6", "");
        let str = str.replace("7", "");
        let str = str.replace("8", "");
        let str = str.replace("9", "");
        if !str.is_empty() {
            println!("不是数字");
            is_number = false;
        }
        if is_number {
            println!("---------")
        }
        println!("{:?}", is_number);
    }
}
